package com.dahaonetwork.smartfactory.interceptor;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.event.Level;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;

import feign.RequestInterceptor;
import feign.RequestTemplate;


@Configuration
public class FeignClientsConfiguration {

	// feign拦截器，依照zuul在过滤链中所做工作类似，将session依次下传
	@Bean
	public RequestInterceptor requestTokenBearerInterceptor(OAuth2ClientContext context) {

		return new RequestInterceptor() {
			/** 得到当前线程中request */
			@Autowired
			HttpServletRequest request;
			// @Autowired
			// private OAuth2ClientContext context;
//			private final Logger LOG = Logger.getLogger(RequestInterceptor.class.getName());
			private final Logger log = LoggerFactory.getLogger(this.getClass());  

			@Override
			public void apply(RequestTemplate requestTemplate) {
				
				log.info( "feign 相互间调用拦截器进行传递信息的配置");
				
				try {
					Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
					OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
					requestTemplate.header("Authorization", "bearer " + details.getTokenValue());
				} catch (Exception e) {
					log.error("获取鉴权认证信息失败", e);
				}
				/*try {
					// 设置请求头
					if (context.getAccessToken() != null && context.getAccessToken().getValue() != null
							&& OAuth2AccessToken.BEARER_TYPE
									.equalsIgnoreCase(context.getAccessToken().getTokenType())) {
						requestTemplate.header("Authorization", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE,
								context.getAccessToken().getValue()));
					}
				} catch (Exception e) {
					LOG.error("获取鉴权认证信息失败", e);
				}*/

				// 得到当前session信息
				/*try {
					HttpSession httpSession = request.getSession();
					requestTemplate.header("Cookie", "SESSION=" + httpSession.getId());
				} catch (Exception e) {
					LOG.error("获取session信息失败", e);
				}*/

			}
		};
	}
	
	

	/**
	 * @Title: oAuth2FeignRequestInterceptor
	 * @Description: 使用spring cloud security提供的feign拦截器，传统的方式并不能奏效
	 * @return OAuth2FeignRequestInterceptor
	 */
	// @Bean
	// @ConditionalOnClass(Feign.class)
	// public OAuth2FeignRequestInterceptor oAuth2FeignRequestInterceptor(
	// final OAuth2ClientContext oauth2ClientContext,
	// final OAuth2ProtectedResourceDetails details) {
	// return new OAuth2FeignRequestInterceptor(oauth2ClientContext, details);
	// }

}